from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
from django.db.models import Sum, Q, Count, F

from rest_framework import viewsets,mixins,generics,permissions, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django.contrib.auth.models import User
from info_sys.models import Supplier, Buyer, Item, OrderItem, Order, goodItem, goodVerfiyImage
from info_sys.serializers import BuyerSerializer, SupplierSerializer, ItemSerializer, OrderItemSerializer,\
    OrderSerializer, goodItemSerializer
import json

# Create your views here.
def allow_all(response):
    """
    解决跨域的问题
    :param response:
    :return:
    """
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    return response


class BuyerViewSet(viewsets.ModelViewSet):
    """
    社区用户记录.
    |-openid: 微信openid
    |-username: 昵称
    |-phone:手机号码
    |-full_name: 真实名字
    |-address: 社区地址
    |-is_verify: 人工审核身份
    """
    queryset = Buyer.objects.all()
    serializer_class = BuyerSerializer

    def create(self, request):
        phone = request.POST.get('phone')
        user = Buyer.objects.filter(phone=phone)
        if user.exists():
            res = {'message': '手机已经注册', 'is_error': True}
            return HttpResponse(json.dumps(res), content_type="application/json")
        else:
            passwd = request.POST.get('password')
            if passwd:
                user = User.objects.create_user(
                    username=f'buyer_{phone}',
                    password=passwd,
                )
                buyer = Buyer(
                    user=user,
                    phone=phone
                )
                buyer.save()
                serialize = BuyerSerializer(buyer, context={'request': request})
                return Response(serialize.data, status=status.HTTP_201_CREATED)
            else:
                res = {'message': '缺少密码', 'is_error': True}
                return HttpResponse(json.dumps(res), content_type="application/json")


class SupplierViewSet(viewsets.ModelViewSet):
    """
    社区用户记录.
    |-openid: 微信openid
    |-username: 昵称
    |-phone:手机号码
    |-full_name: 真实名字
    |-address: 社区地址
    |-is_verify: 人工审核身份
    """
    queryset = Supplier.objects.all()
    serializer_class = SupplierSerializer

    def create(self, request):
        phone = request.POST.get('phone')
        user = Supplier.objects.filter(phone=phone)
        if user.exists():
            res = {'message': '手机已经注册', 'is_error': True}
            return HttpResponse(json.dumps(res), content_type="application/json")
        else:
            passwd = request.POST.get('password')
            if passwd:
                user = User.objects.create_user(
                    username=f'supplier_{phone}',
                    password=passwd,
                )
                supplier = Supplier(
                    user=user,
                    phone=phone
                )
                supplier.save()
                serialize = SupplierSerializer(supplier, context={'request': request})
                return Response(serialize.data, status=status.HTTP_201_CREATED)
            else:
                res = {'message': '缺少密码', 'is_error': True}
                return HttpResponse(json.dumps(res), content_type="application/json")


class ItemViewSet(viewsets.ModelViewSet):
    """
    需求物品.
    |-name: 名称
    |-content:  描述
    |-sup_type: 类别
    |-is_deleted: 失效
    """
    queryset = Item.objects.all().order_by('-created')
    serializer_class = ItemSerializer


class OrderViewSet(viewsets.ModelViewSet):
    """
    需求物品订单.
    |-buyer:  订单发起人
    |-content:  描述
    |-is_verify: 是否审核
    |-is_deleted: 失效
    |-updated: 更新时间
    |-created: 创建时间
    |-order_items: 订单详细信息
    """
    queryset = Order.objects.all().order_by('-created')
    serializer_class = OrderSerializer

    def create(self, request):
        buyer_id = request.POST.get('buyer_id')
        buyer = Buyer.objects.filter(id=buyer_id).first()
        if not buyer:
            res = {'message': '用户不存在', 'is_error': True}
            return HttpResponse(json.dumps(res), content_type="application/json")
        else:
            content = request.POST.get('content')
            order = Order(
                buyer=buyer,
                content=content
            )
            order.save()
            # 添加物品
            try:
                items = request.POST.get('items')
                if items:
                    items = json.loads(items)
                    insert_items = []
                    for item in items:
                        insert_items.append(OrderItem(
                            order_id=order.id,
                            item_id=item['id'],
                            count=item['count']
                        ))
                    OrderItem.objects.bulk_create(insert_items)
            except Exception as e:
                print(e)
            serialize = OrderSerializer(order, context={'request': request})
            return Response(serialize.data, status=status.HTTP_201_CREATED)


class GoodItemViewSet(viewsets.ModelViewSet):
    """
    商品信息发布.
    |-name: 名称
    |-supplier_company_name：商家企业名称
    |-content:  描述
    |-sup_type: 类别
    |-is_deleted: 失效
    |-is_verify: 审核
    """
    queryset = goodItem.objects.all().order_by('-created')
    serializer_class = goodItemSerializer

    def create(self, request):
        supplier_id = request.POST.get('supplier_id')
        supplier = Supplier.objects.filter(id=supplier_id).first()
        if not supplier:
            res = {'message': '用户不存在', 'is_error': True}
            return HttpResponse(json.dumps(res), content_type="application/json")
        else:
            content = request.POST.get('content')
            good = goodItem(
                supplier=supplier,
                name=request.POST.get('name'),
                content=content
            )
            good.save()
            try:
                print(request.FILES)
                img = request.FILES['img']
                if img:
                    print('####imggg------', img)
            except Exception as e:
                print('####create', e)
            serialize = goodItemSerializer(good, context={'request': request})
            return Response(serialize.data, status=status.HTTP_201_CREATED)

    @action(detail=False, methods=['POST'])
    def upload_img(self, request):
        good_id = request.POST.get('good_id')
        good = goodItem.objects.filter(id=good_id).first()
        if not good:
            res = {'message': '商品不存在', 'is_error': True}
            return HttpResponse(json.dumps(res), content_type="application/json")
        else:
            try:
                img = request.FILES['img']
                good_img = goodVerfiyImage(
                    good=good,
                    name=request.POST.get('name', f'{good.id}_{img}'),
                    my_img=img
                )
                good_img.save()
            except Exception as e:
                print(e)
                res = {'message': '上传失败', 'is_error': True}
                return HttpResponse(json.dumps(res), content_type="application/json")

            serialize = goodItemSerializer(good, context={'request': request})
            return Response(serialize.data, status=status.HTTP_200_OK)